package com.iot.manager.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.iot.manager.data.models.DeviceData;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class DataExporter {
    private static final String TAG = "DataExporter";

    public static File exportToCsv(Context context, List<DeviceData> dataList, String deviceId) throws IOException {
        if (dataList == null || dataList.isEmpty()) {
            throw new IOException("No data to export");
        }

        // 创建导出目录
        File exportDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "IoT_Manager_Exports");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }

        // 创建CSV文件
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File csvFile = new File(exportDir, "device_" + deviceId + "_data_" + timestamp + ".csv");

        try (FileWriter writer = new FileWriter(csvFile)) {
            // 写入CSV头
            writer.append("设备ID,时间,温度(°C),湿度(%)\n");

            // 写入数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            for (DeviceData data : dataList) {
                writer.append(deviceId)
                      .append(",")
                      .append(dateFormat.format(data.getTimestamp()))
                      .append(",")
                      .append(String.valueOf(data.getTemperature()))
                      .append(",")
                      .append(String.valueOf(data.getHumidity()))
                      .append("\n");
            }
        }

        return csvFile;
    }
} 